import * as Form from "@radix-ui/react-form";
import "./teachchForm.css";
import { baseInfoPersonForm } from "../utils/data";
import { createBaseInfo } from "../apis/form";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import logo from "../assets/dance-logo.jpg";
import { pca, pcaa } from "area-data"; // v3 or higher
import "react-area-linkage/dist/index.css"; // v2 or higher
import { AreaSelect, AreaCascader } from "react-area-linkage";
import { useState } from "react";

const FormDemo = () => {
  const [category, setCategory] = useState(null);
  const [area, setArea] = useState([]);
  const [alreadySubmit, setAlreadySubmit] = useState(false);
  const [imageData, setImageData] = useState(null);

  const handleSubmit = async (event) => {
    let data = Object.fromEntries(new FormData(event.currentTarget));

    event.preventDefault();
    // 这里可以添加提交表单的逻辑
    if (area?.length === 0) {
      toast.error("请选择地区");
      return;
    }

    if (!imageData) {
      toast.error("请上传个人照片");
      return;
    }
    data.region = area?.join("/");
    data = { ...data, ...imageData };
    console.log("Submitted name:", data);
    const resp = await createBaseInfo(data);
    console.log(resp, resp.data?.code);
    if (resp.data?.code === 0) {
      toast.success("申请成功");
      setAlreadySubmit(true);
    } else {
      toast.error(resp?.data?.msg);
    }
  };

  const handleAreaChange = (val) => {
    console.log("area", val);
    setArea(val);
  };

  const renderFormItem = (item) => {
    switch (item.type) {
      case "select":
        return (
          <Form.Control asChild className="mt-[10px]">
            <select
              className="Input"
              required
              onChange={(e) => {
                if (item.key === "category") {
                  setCategory(e.target.value);
                }
              }}
            >
              {item.options?.map((item) => {
                return (
                  <option value={item.value} key={item.value}>
                    {item.label}
                  </option>
                );
              })}
            </select>
          </Form.Control>
        );

      case "textarea":
        return (
          <Form.Control asChild className="mt-[10px]">
            <textarea className="Textarea" rows="4" required />
          </Form.Control>
        );

      case "number":
        return (
          <Form.Control asChild className="mt-[10px]">
            <input className="Input" type="number" required />
          </Form.Control>
        );

      case "email":
        return (
          <Form.Control asChild className="mt-[10px]">
            <input className="Input" type="email" required />
          </Form.Control>
        );

      case "file":
        return (
          <>
            <Form.Control asChild className="mt-[10px] hidden">
              <input
                type="file"
                id="fileInput"
                onChange={(event) => {
                  const file = event.target.files[0]; // 获取选择的文件
                  console.log("file", file);
                  if (file) {
                    const fileName = file.name; // 获取文件名称
                    const reader = new FileReader(); // 创建 FileReader 对象

                    // 当文件被读取时，将其转换为 base64 编码
                    reader.onload = function (e) {
                      var img = new Image();
                      img.src = e.target.result;

                      img.onload = function () {
                        var canvas = document.createElement("canvas");
                        var ctx = canvas.getContext("2d");

                        // 可选：调整canvas尺寸以改变图片分辨率
                        canvas.width = 500; // 或者其他值
                        canvas.height =
                          (img.naturalHeight * canvas.width) / img.naturalWidth;

                        // 清除画布
                        ctx.clearRect(0, 0, canvas.width, canvas.height);

                        // 绘制图片到画布
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                        // 压缩图片并获取Data URL
                        var compressedDataURL = canvas.toDataURL(
                          "image/jpeg",
                          0.6
                        ); // 0.8是质量参数，范围0-1

                        // 现在compressedDataURL包含了压缩后的图片数据，可以用于显示或上传
                        console.log(compressedDataURL);
                        const base64String = compressedDataURL;
                        console.log("文件名称:", fileName);
                        console.log("Base64 编码:", base64String);
                        const pathList = base64String.split(",");
                        console.log(pathList);
                        const picFile = pathList[pathList?.length - 1];
                        setImageData({
                          base64String,
                          picFile,
                          picFileName: fileName,
                        });
                      };

                      // 这里你可以将 base64 字符串设置到一个 img 元素的 src 属性来显示图片
                    };

                    // 读取文件为 Data URL（base64 编码）
                    reader.readAsDataURL(file);
                  }
                }}
              />
            </Form.Control>

            <button
              type="button"
              className="Input mt-[10px] flex items-center justify-center"
              style={{
                justifyContent: "center",
              }}
              onClick={() => {
                document.getElementById("fileInput").click();
              }}
            >
              {imageData ? "重新选择" : "选择文件"}
            </button>
            {imageData && (
              <img
                src={imageData.base64String}
                className="mt-[20px] w-[100%]"
                alt=""
              />
            )}
          </>
        );

      // case "rangenumber":
      //   return (
      //     <Form.Control asChild className="mt-[10px]">
      //       <RangeNumber></RangeNumber>
      //     </Form.Control>
      //   );

      case "area":
        return (
          <div className="flex">
            <AreaSelect
              type="text"
              level={2}
              data={pca}
              onChange={handleAreaChange}
            />
          </div>
        );

      case "date":
        return (
          <Form.Control asChild className="mt-[10px]">
            <input
              type="date"
              className="Date"
              name={item.key}
              required
              defaultValue={item.default}
            />
          </Form.Control>
        );
    }

    return (
      <Form.Control asChild className="mt-[10px]">
        <input className="Input" required />
      </Form.Control>
    );
  };

  return (
    <div>
      <ToastContainer></ToastContainer>
      <div className="px-[20px] py-[20px] text-center flex justify-center mb-[10px] mt-[20px] logoContainer pb-[20px] pt-[10px] flex-col items-center">
        <img className="w-[160px] mb-[40px]" src={logo} alt="" />
        <h2 className="text-[24px] font-bold text-center">
          中华儿童文化艺术促进会舞蹈专业委员会注册教师申请
        </h2>
        <div
          className="mt-[20px]"
          style={{
            textAlign: "left",
            lineHeight: "26px",
            letterSpacing: "1px",
          }}
        >
          <h3 className="text-[20px] mb-[5px]">注册教师申请条件</h3>
          <div>1、年满18周岁，男女不限；</div>
          <div>2、舞蹈教育、编导、表演、艺术管理等舞蹈相关专业毕业；</div>
          <div>3、从事舞蹈教育、艺术传播相关工作者；</div>
          <div>4、获得文旅部认定的教师培训证书6级以上；</div>
          <div>
            5、认可中华儿童文化艺术促进会舞蹈专业委员会管理章程，愿意为社会舞蹈教育普及推广工作做出贡献者。
          </div>
        </div>
      </div>
      <div className="px-[20px] py-[20px]">
        <Form.Root className="FormRoot" onSubmit={handleSubmit}>
          {baseInfoPersonForm.map((item) => {
            if (item.key === "serialNumber" && category !== "expiry")
              return null;

            return (
              <Form.Field key={item.key} className="FormField" name={item.key}>
                <div>
                  <Form.Label className="FormLabel font-bold">
                    {item.label}
                  </Form.Label>

                  {/* <Form.Message className="FormMessage" match="typeMismatch">
                Please provide a valid email
              </Form.Message> */}
                </div>
                {renderFormItem(item)}
                {/* <Form.Control asChild className="mt-[10px]">
                <input className="Input" required />
              </Form.Control> */}
                {item.key === "email" && (
                  <Form.Message
                    className="FormMessage mt-[10px] text-[red]"
                    match="typeMismatch"
                  >
                    请输入正确的邮箱
                  </Form.Message>
                )}
                {item.key === "cardNo" && (
                  <Form.Message
                    className="FormMessage mt-[10px] text-[red]"
                    match={(val) => {
                      const regex =
                        /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}([0-9Xx])?$/;
                      console.log("regex.test(val)", regex.test(val));
                      return !regex.test(val);
                    }}
                  >
                    请输入正确的身份证
                  </Form.Message>
                )}
                {item.key === "mobile" && (
                  <Form.Message
                    className="FormMessage mt-[10px] text-[red]"
                    match={(val) => {
                      console.log("val", val, val?.length, val?.length === 11);
                      return val?.length !== 11;
                    }}
                  >
                    请输入正确的电话
                  </Form.Message>
                )}
                <Form.Message
                  className="FormMessage mt-[10px] text-[red]"
                  match="valueMissing"
                >
                  请填写{item.label}
                </Form.Message>
              </Form.Field>
            );
          })}

          <Form.Submit asChild>
            <button
              type="submit"
              className="Button mt-[20px]"
              disabled={alreadySubmit}
            >
              提交
            </button>
          </Form.Submit>
        </Form.Root>
      </div>
    </div>
  );
};

export default FormDemo;
